<style>
  .sample {
    width: 120px;
    height: 40px;
    line-height: 40px;
    background: rgba(0,0,0,0.5);
    overflow: hidden;
    box-shadow: 0 0 5px #000;
    color: #fff;
    text-align: center;
    padding: 10px;
    position: absolute;
  }
  .sample.active {
    background: rgba(0,0,0,0.75);
    color: #fff;
  }
  .Done {
    width: 100%;
    height: 40px;
  }

  .Dtwo {
    width: 100%;
    height: 30px;
  }

  .bm-view {
    width: 100%;
    height: 960px;
  }
</style>

<template>
  <div>
    <!--顶部容器-->
    <!--<div class="Done">-->
    <!--</div>enableCloseOnClick-->
    <!--中部容器-->
    <baidu-map
      class="bm-view"
      @mousemove="syncPolygon"
      @dblclick="DoubleClick"
      @rightdblclick="Rightdblclick"
      @maptypechange="MapType"
      @rightclick="newPolygon"
      @ready="MapHandler"
      :center="this.center"
      :zoom="this.zoom"
      :double-click-zoom="false"
      :min-zoom="10"
      :scroll-wheel-zoom="true"
      :continuous-zoom="true"
      @moving="syncCenterAndZoom"
      @moveend="syncCenterAndZoom"
      @zoomend="syncCenterAndZoom"
      @click="paintPolygon"
    >
      <bm-map-type :map-types="['BMAP_NORMAL_MAP', 'BMAP_HYBRID_MAP']" anchor="BMAP_ANCHOR_TOP_LEFT"></bm-map-type>
      <!--右下加入定位控件-->
      <bm-geolocation anchor="BMAP_ANCHOR_BOTTOM_RIGHT" :showAddressBar="true" :autoLocation=true></bm-geolocation>
      <!--绘制多边形-->
      <bm-polygon :path="path" v-for="path of polygon.paths"
                  :stroke-opacity="0.5"
                  :stroke-weight="2"
                  :editing="editState"
                  :fill-color="color"
                  :strokeColor="color"
                  :fillOpacity=polygonOpacity
                  @mouseover="enterPolygon"
                  @mouseout = "outPolygon"
                  @lineupdate="updatePolygonPath"/>

      <bm-boundary name="三亚市"
                   :mass-clear=false
                   @mouseover="enterSanYa"
                   @mouseout="outSanYa"
                   :strokeWeight="2"
                   strokeStyle="solid"
                   :fillColor=this.SanYaColor
                   strokeColor="rgba(91, 4, 13, 1)"></bm-boundary>
      <bm-boundary name="三亚市吉阳区"
                   @mouseover="enterJiYang"
                   :mass-clear=false
                   @mouseout="outJiYang"
                   strokeStyle="dashed"
                   :strokeWeight="2"
                   :fillColor=this.JiYangColor
                   strokeColor="none"></bm-boundary>
      <bm-boundary name="三亚市海棠区"
                   @mouseover="enterHaiTang"
                   @mouseout="outHaiTang"
                   strokeStyle="dashed"
                   :mass-clear=false
                   :strokeWeight="2"
                   :fillColor=this.HaiTangColor
                   strokeColor="none"></bm-boundary>
      <bm-boundary name="三亚市天涯区"
                   :mass-clear=false
                   @mouseover="enterTianYa"
                   @mouseout="outTianYa"
                   strokeStyle="dashed"
                   :strokeWeight="2"
                   :fillColor=this.TianYaColor
                   strokeColor="none"></bm-boundary>
      <bm-boundary name="三亚市崖州区"
                   @mouseover="enterYaZhou"
                   @mouseout="outYaZhou"
                   :mass-clear=false
                   strokeStyle="dashed"
                   :strokeWeight="2"
                   :fillColor=this.YaZhouColor
                   strokeColor="none"></bm-boundary>

    </baidu-map>

    <!--底部容器-->
    <div class="Dtwo">
      <span>经度:</span>
      <el-input v-model.number="center.lng" clearable style="width:10%" class="input-with-select"
                placeholder="经度"></el-input>
      <span>纬度:</span>
      <el-input v-model.number="center.lat" clearable style="width:10%" class="input-with-select"
                placeholder="纬度"></el-input>
      <span>缩放级别:</span>
      <el-input v-model.number="zoom" clearable style="width:10%" class="input-with-select"
                placeholder="缩放比例"></el-input>
      <el-button type="primary" size="mini" round @click="toggle('polygon')" :disabled="notDraw ">绘制</el-button>
      <el-button type="success" size="mini" round @click="showSave" >展示个人全部</el-button>
      <el-button type="danger" size="mini" round @click="clearAll">清除全部</el-button>
      <el-button type="primary" size="mini" round @click="GoIndex">返回首页</el-button>
      <!--颜色修改器-->
      <el-color-picker
        align="center"
        size="medium"
        v-model="color"
        show-alpha
        :predefine="predefineColors">
      </el-color-picker>
    </div>
    <map-info ref="addinfo" :Whereply="Whereply"></map-info>
  </div>

</template>

<script>
  //引入map实例
  import BaiduMap from 'vue-baidu-map/components/map/Map.vue'
  import mapInfo from './addInfoFrom.vue'
  import {deleOneCover,getOneCover,saveCover,getAllCover,getCouList,getStuList, UpStuCou,deleteStu,findLikeStus} from '@/api/userApi' //导入接口工具
  // import mapInfo  from './addInfoFrom.vue'
  export default {
    //模板注册
    components: {
      mapInfo:mapInfo,
      BaiduMap,
    },
    data() {
      return {
        polygonPath: [], //刚刚画完的覆盖物
        notDraw: false,   //绘制按钮状态
        polygonOpacity:0.7,
        color: 'rgba(255, 0, 115, 0.78)', //多边形颜色
        predefineColors: [ //预定义颜色
          '#ff4500',
          '#ff8c00',
          '#ffd700',
          '#90ee90',
          '#00ced1',
          '#1e90ff',
          '#c71585',
          'rgba(255, 69, 0, 0.68)',
          'rgb(255, 120, 0)',
          'hsv(51, 100, 98)',
          'hsva(120, 40, 94, 0.5)',
          'hsl(181, 100%, 37%)',
          'hsla(209, 100%, 56%, 0.73)',
          'rgba(255, 0, 0, 1)'
        ],//预定义颜色
        editState: false,  //多边形编辑状态
        center: {lng: 109.564187, lat: 18.26258},//中心经纬度经度： 109.564187 , 维度： 18.26258
        zoom: 14,
        //多边形数据
        polygon: {
          paths: [],
          zindex:[],
          color:[],
        },
        Whereply:null, //鼠标所在的覆盖物，实时同步给子组件
        plydata: [], //收集数据库返回的所有覆盖物
        targerCover:null, //实时的多边形收集器
        targer:[],      //覆盖物收集器
        SanYaColor:"none",
        JiYangColor: 'none',
        YaZhouColor: "none",
        TianYaColor: "none",
        HaiTangColor: "none",
        isRetudata:null//提交某个覆盖物之后，返回来的数据放这儿
      }
    },
    methods: {
      GoIndex(){
        //this.$router.push({path: '/Home.vue',query:{ ddd:'332'}});
        this.$router.push({name: 'Home',params:{ }});

      },
      //显示地块列表
      showSave() {
        //  console.log("params", this.$route.params.ddd)
        var that = this;//将vue当前的this再次赋值，在下面才能继续调用
        getAllCover().then(response => {
          map.clearOverlays()  //清除地图上所有的覆盖物
          const data = response.data//获取后台响应的原始数据
          this.plydata = data.data  //收集到全局
          console.log( "data",data)
          boundary();
          function boundary() {
            var conun = data.data.length
            //   var conun = that.plydata.length
            for (var j = 0; j < conun; j++) {
              (function (index) {
                var ply = new BMap.Polygon(that.plydata[j].mapCover, {
                  fillColor: that.plydata[j].color,
                  strokeWeight: 2,
                  strokeOpacity:0.4,
                  fillOpacity:0.4,
                  strokeColor: that.plydata[j].color
                }); //建立多边形覆盖物
                map.addOverlay(ply);  //添加覆盖物
                var infoWindow = new BMapLib.SearchInfoWindow(map, that.plydata[j].name, {
                  title: "地块名", //标题
                  width: 80, //宽度
                  height: 60, //高度
                  panel: "panel", //检索结果面板
                  enableAutoPan: true, //自动平移
                  searchTypes: []
                });
                var WindowState = true
                var polygonMenu=new BMap.ContextMenu();
                var cover = that.plydata[j]  //获取当前索引的覆盖物信息
                //把当前覆盖物赋值给外部组件,用于信息回填

                polygonMenu.addItem(new BMap.MenuItem('编辑内容',  function addMapInfo() {
                  that.$refs.addinfo.showForm = !that.$refs.addinfo.showForm //弹出表单
                  WindowState = false//关窗
                } ));
                polygonMenu.addItem(new BMap.MenuItem('修改地形',  function editOverlay() {
                  WindowState = false
                  ply.enableEditing() //开启编辑;
                } ));
                polygonMenu.addItem(new BMap.MenuItem('完成编辑',  function saveOverlay() {
                  WindowState = true
                  ply.disableEditing() //完成编辑;
                } ));
                polygonMenu.addItem(new BMap.MenuItem('删除',  function deleteOverlay() {
                  deleOneCover(ply.getPath()).then(response => {
                    map.removeOverlay(ply);
                  })

                } ));
                ply.addContextMenu(polygonMenu);//添加右键菜单

                //添加鼠标滚轮事件
                map.addEventListener("zoomend", function (e) {
                  //条件：缩放几倍小于12就隐藏覆盖物,否则就显示
                  if (that.zoom < 12) {
                    ply.hide()
                  } else {
                    ply.show()
                  }
                })
                //鼠标经过事件
                ply.addEventListener('mouseover', function () {
                  ply.setFillOpacity(0.6)
                  ply.setStrokeOpacity(0.6)
                  //把当前的覆盖物放到全局
                  that.$refs.addinfo.ply = cover
                  //鼠标移动事件
                  ply.addEventListener("mousemove", function (e) {
                    if (WindowState===true) {
                      infoWindow.open(e.point);
                    }else if (WindowState===false) {
                      infoWindow.close();
                    }
                  })//mousemove
                })//mouseover
                //鼠标离开事件
                ply.addEventListener('mouseout', function () {
                  ply.setFillOpacity(0.4)
                  ply.setStrokeOpacity(0.4)
                  infoWindow.close(); //关窗
                })//mouseout
              })(j)

            }//for
          }

        })
      },
      /*===============================================业====务====事====件=============================================*/
      //实时将多边形转成覆盖物
      TurnCover(){
        map.clearOverlays()  //清除地图上所有的覆盖物,避免重叠
        var that = this
        boundary();
        function boundary() {
          var conun = that.targer.length
          for (var j = 0; j < conun; j++) {
            (function (index) {
              var color = that.targer[j].K.strokeColor//未保存覆盖物默认颜色
              if (that.isRetudata!=null) {
                var isdata = []//"已保存的数据"
                var str =[] //"为保存的数据"
                //只获取0索引的坐标进行判断，坐标相同的概率是10亿分之一，因此只需要取一条
                isdata.push(that.isRetudata.mapCover[0].lng,that.isRetudata.mapCover[0].lat)
                for (let i = 0;i<that.targer[j].Qn.length;i++){
                  str.push(that.targer[j].Qn[i].lng,that.targer[j].Qn[i].lat)//收集"未保存"覆盖物的点数组字符串
                }
                //判断"未保存"是否包含"已保存",如果已包含，则用已保存的覆盖物的颜色，否则用默认的
                if (str.toString().indexOf(isdata.toString()) != -1===true){
                  color ="rgba(255, 0, 0, 0.88)"
                }
              }
              var ply = new BMap.Polygon(that.targer[j].Qn, {fillColor: color,strokeWeight: 2, strokeColor: color}); //建立多边形覆盖物
              map.addOverlay(ply);  //添加覆盖物
              //  创建右键菜单
              var cover = that.targer[j]  //获取当前索引的覆盖物信息
              var infoWindow = new BMapLib.SearchInfoWindow(map, "第"+index+"个", {
                title: "地块信息", //标题
                width: 80, //宽度
                height: 60, //高度
                panel: "panel", //检索结果面板
                enableAutoPan: true, //自动平移
                searchTypes: []
              });
              var WindowState = true
              /*====================右===============键===============菜===============单==========================*/
              var polygonMenu=new BMap.ContextMenu();
              polygonMenu.addItem(new BMap.MenuItem('录入数据',  function addMapInfo() {
                if (ply.getFillColor()!=='rgba(255, 0, 0, 0.88)') {
                  //如果覆盖物颜色等于'rgba(255, 0, 0, 0.88)'，表明这个覆盖物数据库中的
                  that.$refs.addinfo.showForm = !that.$refs.addinfo.showForm //弹出表单
                  WindowState = false//关窗
                }else {
                  alert("已录过数据了")
                }
              } ));
              polygonMenu.addItem(new BMap.MenuItem('编辑地形',  function editOverlay() {
                if (ply.getFillColor()!=='rgba(255, 0, 0, 0.88)') {
                  WindowState = false
                  ply.enableEditing() //开启编辑;
                }else {
                  alert("不可编辑")
                  ply.disableEditing() //完成编辑;
                }
              } ));
              polygonMenu.addItem(new BMap.MenuItem('完成编辑',  function saveOverlay() {
                WindowState = true
                ply.disableEditing() //完成编辑;
              } ));
              polygonMenu.addItem(new BMap.MenuItem('删除地形',  function deleteOverlay() {
                deleOneCover(that.Whereply.Qn).then(response => {
                  map.removeOverlay(ply);
                  console.log("删除成功")
                })
              } ));
              polygonMenu.addItem(new BMap.MenuItem('提交',  function submit() {
                if (ply.getFillColor()!=='rgba(255, 0, 0, 0.88)') {
                  if (that.$refs.addinfo.form.area != null || that.$refs.addinfo.form.name != null) {
                    let name = that.$refs.addinfo.form.name;
                    let area = that.$refs.addinfo.form.area;
                    let state = that.$refs.addinfo.form.state
                    saveCover(that.Whereply.Qn, that.Whereply.K.fillColor, name, area, state).then(response => {
                      const data = response.data//获取后台响应的原始数据,不用再循环
                      console.log(data)
                      state = true
                      //把当前覆盖物赋值给外部组件,用于信息回填
                      that.$refs.addinfo.ply = data
                      WindowState = true//开启窗口
                      that.isRetudata = data
                      // that.$options.methods.SuccessInfo()
                      ply.setFillColor('rgba(255, 0, 0, 0.88)')//保存成功的覆盖物变色区分
                    })
                  } else {
                    alert("请先录入数据")
                  }
                }else {
                  alert("不可重复提交")
                }
              } ));
              ply.addContextMenu(polygonMenu);//添加右键菜单
              /*=======================================事=======================件==========================*/
              //进入覆盖物事件（弹窗）
              ply.addEventListener('mouseover', function () {
                that.Whereply=ply//把当前的覆盖物放到全局
                ply.addEventListener("mousemove", function (e) {
                  if (WindowState===true) {
                    infoWindow.open(e.point);
                  }else if (WindowState===false) {
                    infoWindow.close();
                  }

                })//mousemove
              })//mouseover
              // 覆盖物属性变化就调用
              ply.addEventListener('lineupdate', function () {

              })
              //离开覆盖物事件(关窗)
              ply.addEventListener('mouseout', function () {
                infoWindow.close();
              })//mouseout

              //鼠标滚轮事件
              map.addEventListener("zoomend", function (e) {
                //条件：缩放几倍小于12就隐藏覆盖物,否则就显示
                if (that.zoom < 12) {
                  ply.hide()
                } else {
                  ply.show()
                }
              })
              /*==========================================事=======================件==========================*/
            })(j)
          }//for
        }
        let name = 'polygon'
        this[name].editing = false //关闭绘制模式
        this.notDraw = false
        this.editState = false  //关闭编辑模式
      },


      //清除覆盖物
      clearAll() {
        //   this.polygon.paths = []//把覆盖物置空
        var allOverlay = map.getOverlays();
        map.clearOverlays()  //清除地图上所有的覆盖物
        // map.removeOverlay();
        this.editState = false  //,同时关闭编辑模式
        //打印多边形数据
        console.log("覆盖物被清空", allOverlay)
      },
      //多边形变化就调用 （lineupdate）
      updatePolygonPath(e) {
        this.targerCover = e.target   //实时的多边形对象存到全局
      },
      //绘制多边形
      toggle(name) {
        //  let name = 'polygon'
        this[name].editing = true //开启绘制模式
        this.notDraw = true//开启绘制按钮禁用状态
        this.editState = false  //关闭编辑模式
        this.$refs.addinfo.form.area = null  //置空信息表单，避免数据被重用
        this.$refs.addinfo.form.name = null
        console.log("绘制状态",this[name].editing)
      },


      /*===================================================属====性====事====件===============================================*/
      //进入多边形触发
      enterPolygon(){
        //高亮多边形
        let name = 'polygon'
        if (this[name].editing !== true || this.editState!== true){
          this.polygonOpacity = 0.9
        }
      },
      //离开多边形触发
      outPolygon(){
        //还原
        this.polygonOpacity = 0.7
      },
      //进入三亚
      enterSanYa(){

      },
      //离开三亚
      outSanYa(){

      },
      //进入崖州
      enterYaZhou(){
        if (this.zoom < 12){
          this.YaZhouColor = "rgba(15, 206, 69, 0.49)"
        }
      },
      //离开崖州
      outYaZhou(){
        this.YaZhouColor = "none"
      },
      //进入天涯
      enterTianYa(){
        if (this.zoom < 12){
          this.TianYaColor = "rgba(255, 128, 0, 0.76)"
        }
      },
      //离开天涯
      outTianYa(){
        this.TianYaColor = "none"
      },
      //进入海棠
      enterHaiTang(){
        if (this.zoom < 12){
          this.HaiTangColor = "rgba(0, 64, 255, 0.66)"

        }
      },
      //离开海棠
      outHaiTang(){
        this.HaiTangColor = "none"
      },
      //进入吉阳
      enterJiYang(){
        if (this.zoom < 12){
          this.JiYangColor = "rgba(255, 0, 140, 0.44)"
        }
      },
      //离开吉阳
      outJiYang(){
        this.JiYangColor = "none"
      },
      /*=========================监====听====事====件==================================================================================*/
      //mousemove 监听鼠标位移
      syncPolygon(e) {
        window.e = e
        //缩放级别大于11，鼠标再次滑动，机会清除所有行政区颜色
        if (this.zoom>11){
          this.JiYangColor= 'none',
            this.YaZhouColor= "none",
            this.TianYaColor= "none",
            this.HaiTangColor= "none"
        }
        if (!this.polygon.editing) {
          return
        }
        const {paths} = this.polygon
        if (!paths.length) {
          return
        }
        const path = paths[paths.length - 1]
        if (!path.length) {
          return
        }
        if (path.length === 1) {
          path.push(e.point)
        }
        this.$set(path, path.length - 1, e.point)
      },
      //左键单击 click
      paintPolygon(e) {
        console.log("鼠标点击处经度：", e.point.lng, ",", "维度：", e.point.lat)
        //绘制覆盖物
        if (!this.polygon.editing) {
          return
        }

        //获取实时的经纬度
        const {paths} = this.polygon
        !paths.length && paths.push([])
        paths[paths.length - 1].push(e.point)
      },
      //右键单击事件  rightclick
      newPolygon() {
        this.notDraw = false//关闭绘制按钮禁用状态
        this.editState = false//关闭绘制物编辑状态
        console.log("所有多边形", this.polygon.paths)
        if (!this.polygon.editing) {
          return
        }
        const {paths} = this.polygon
        if (!paths.length) {
          paths.push([])
        }
        const path = paths[paths.length - 1]
        path.pop()
        if (path.length) {
          paths.push([])
        }

        this.polygon.paths = []
        this.targer.push(this.targerCover)
        this.TurnCover() //多边形转换为覆盖物
        // this.isRetudata = null //清空上次提交的数据，防止下次无法提交
      },

      //地图缩放结束后触发
      syncCenterAndZoom(e) {
        //缩放级别大于11后，还原所有行政区颜色
        if (this.zoom>12){
          this.SanYaColor="none",
            this.JiYangColor= 'none',
            this.YaZhouColor= "none",
            this.TianYaColor= "none",
            this.HaiTangColor= "none"
          //缩放级别小于12后，显示所有行政区颜色
        }else if (this.zoom<12){
          this.YaZhouColor = "rgba(15, 206, 69, 0.49)"
          this.TianYaColor = "rgba(255, 128, 0, 0.76)"
          this.HaiTangColor = "rgba(0, 64, 255, 0.66)"
          this.JiYangColor = "rgba(255, 0, 140, 0.44)"
        }

        const {lng, lat} = e.target.getCenter()
        //  console.log("经度：", lng, ",", "维度：", lat)
        this.center.lng = lng
        this.center.lat = lat
        this.zoom = e.target.getZoom()
      },

      //左键双击  dblclick
      DoubleClick() {
        console.log("双击了")
      },
      Rightdblclick() {
        console.log("双击了",)
      },
      //地图类型变化时触发
      MapType() {
        console.log("地图类型变化了 ")
      },
      //地图初始化
      MapHandler({BMap, map}) {
        window.map = map;//将map变量存储在全局
        map.setCenter("三亚市");  // 设置地图显示的城市 此项是必须设置的
        var bdary = new BMap.Boundary();//创建行政区域搜索的对象实例

        //添加鼠标滚轮事件
        map.addEventListener("zoomend", function (e) {
          if (e.target.Va > 11) {
            console.log("鼠标", e.target.Va)
          }
        })
        function getBoundary() {
          //三亚市遮罩+++++++++
          bdary.get("三亚市", function (rs) {       //获取行政区域
            var EN_JW = "180, 90;";         //东北角
            var NW_JW = "-180,  90;";       //西北角
            var WS_JW = "-180, -90;";       //西南角
            var SE_JW = "180, -90;";        //东南角
            //4.添加环形遮罩层
            var ply1 = new BMap.Polygon(rs.boundaries[0] + SE_JW + SE_JW + WS_JW + NW_JW + EN_JW + SE_JW, {
              strokeColor: "none",  //线颜色
              fillColor: "rgba(244, 244, 244, 1)",  //填充颜色
              fillOpacity: 1,     //线透明度
              strokeWeight:  0.005,       //线宽度

            }); //建立多边形覆盖物
            //鼠标进入遮罩触发
            ply1.disableMassClear()//禁止被清除
            ply1.addEventListener("mouseover", function () {

            })
            map.addOverlay(ply1);
          });
        }
        setTimeout(function () {
          getBoundary();
        }, 500);

      }//MapHandler
    },
    mounted() {
      //   var oneDev = [{lat: 18.431548, lng: 109.439006}, {lat: 18.334937, lng: 109.380364}, {lat: 18.338781, lng: 109.526393}] //样本
    },

  }
</script>

